//
//  WFAgricultureUploadViewController.m
//  WisdomFarm
//
//  Created by sky on 2018/2/18.
//  Copyright © 2018年 sky. All rights reserved.
//

#import "WFAgricultureUploadViewController.h"
#import "WFServiceTableViewCell.h"
#import "WFServiceCheckBoxCell.h"
#import "WFServiceSectionHeaderView.h"
#import "WFWFTextViewCell.h"
#import "WFUploadImageCell.h"
#import "WFSeparatorTableViewCell.h"

#import "WFButtonTableFooterView.h"
#import "UITableViewCell+WFHeight.h"
#import "WFPickerViewController.h"
#import "WFServiceRequest.h"
#import <SkyCore/NSString+SCUtils.h>

@interface WFAgricultureUploadViewController ()<WFPickerViewControllerDelegate>

@property (nonatomic, strong) WFServiceTableViewCell *cropCell;
@property (nonatomic, strong) WFServiceCheckBoxCell *modeCell;
@property (nonatomic, strong) WFServiceTableViewCell *categoryCell;
@property (nonatomic, strong) WFServiceTableViewCell *phaseCell;

@property (nonatomic, strong) WFSeparatorTableViewCell *descSeparator;
@property (nonatomic, strong) WFServiceSectionHeaderView *descHeader;
@property (nonatomic, strong) WFWFTextViewCell *descCell;

@property (nonatomic, strong) WFSeparatorTableViewCell *imageSeparator;
@property (nonatomic, strong) WFServiceSectionHeaderView *imageHeader;
@property (nonatomic, strong) WFUploadImageCell *imageCell;

@property (nonatomic, strong) WFButtonTableFooterView *footerView;

@property (nonatomic, strong) WFPickerViewController *pickerController;
@property (nonatomic, weak) WFServiceTableViewCell *currentPickerCell;

@property (nonatomic, strong) NSArray<NSArray<__kindof UITableViewCell *> *> *sections;

@end


static NSArray<NSString *> *wf_cropNames;
static NSDictionary<NSString *, NSArray<NSString *> *> * wf_phaseNames;
static NSDictionary<NSString *, NSArray<NSString *> *> * wf_categoryNames;

@implementation WFAgricultureUploadViewController


- (instancetype)init
{
    self = [super init];
    if (self) {
        wf_cropNames = @[ @"双季早稻", @"双季晚稻", @"单季稻", @"油菜", @"茶叶", @"杨梅", @"柑橘", @"葡萄", @"大小麦", @"草莓", @"番茄", @"西瓜", @"枇杷", @"南美白对虾", @"桃子" ];
        wf_phaseNames = @{
                          @"双季早稻" : @[ @"播种",@"出苗",@"三叶",@"移栽",@"返青",@"分蘖",@"拔节",@"孕穗",@"抽穗",@"灌浆",@"成熟" ],
                          @"双季晚稻" : @[ @"播种",@"出苗",@"三叶",@"移栽",@"返青",@"分蘖",@"拔节",@"孕穗",@"抽穗",@"灌浆",@"成熟" ],
                          @"单季稻" : @[ @"播种",@"出苗",@"三叶",@"移栽",@"返青",@"分蘖",@"拔节",@"孕穗",@"抽穗",@"灌浆",@"成熟" ],
                          @"油菜" : @[ @"苗期",@"移栽越冬期",@"蕾薹期",@"开花结荚期",@"成熟收割期" ],
                          @"茶叶" : @[ @"越冬生长期",@"萌芽期",@"萌芽采摘期",@"采摘期" ],
                          @"杨梅" : @[ @"越冬期",@"萌芽期",@"开花期",@"幼果期",@"发白期",@"转色期",@"成熟期" ],
                          @"柑橘" : @[ @"休眠期",@"萌芽期",@"显蕾期",@"春梢生长期",@"开花期",@"生理落果期",@"果实生长期",@"果实膨大期",@"着色期",@"果实成熟期" ],
                          @"葡萄" : @[ @"越冬期",@"萌芽展叶期",@"开花期",@"坐果期",@"膨大着色期",@"成熟采摘期" ],
                          @"大小麦" : @[ @"播种出苗期",@"分蘖越冬期",@"拔节孕穗期",@"灌浆成熟期" ],
                          @"草莓" : @[ @"育苗定植期",@"缓苗与营养生长期",@"花期",@"花果期",@"盛华盛果期" ],
                          @"番茄" : @[ @"播种期",@"定植期",@"苗期",@"第一花序",@"第一大果" ],
                          @"西瓜" : @[ @"播种育苗期",@"移栽定植期",@"伸蔓期",@"开花膨瓜期",@"成熟采摘期" ],
                          @"枇杷" : @[ @"开花期",@"幼果期",@"膨大期",@"成熟期" ],
                          @"南美白对虾" : @[ @"放苗期",@"养殖期",@"捕捞期" ],
                          @"桃子" : @[  ],
                          };

        wf_categoryNames = @{
                             @"双季早稻" : @[ @"中早39",@"中嘉早17",@"金早47",@"甬籼15",@"金早09" ],
                             @"双季晚稻" : @[ @"绍粳",@"宁88",@"甬优12",@"Y两优689",@"金早09" ],
                             @"单季稻" : @[ @"中浙优8号",@"甬优15",@"甬优9号",@"中浙优1号",@"春优84",@"甬优538",@"嘉优5号" ],
                             };
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"农情上报";
    @weakify(self);
    self.cropCell = [WFServiceTableViewCell new];
    self.cropCell.titleLabel.text = @"作物";
    self.cropCell.onClick = ^(WFServiceTableViewCell *cell, NSIndexPath *indexPath) {
        @strongify(self);
        [self onCrop];
    };
    self.modeCell = [WFServiceCheckBoxCell new];
    self.modeCell.titleLabel.text = @"种植模式";
    self.modeCell.groupView.titles = @[ @"大田作物", @"设备作物" ];
    self.modeCell.groupView.allowsMultiSelection = NO;
    
    self.categoryCell = [WFServiceTableViewCell new];
    self.categoryCell.titleLabel.text = @"作物品种";
    self.categoryCell.onClick = ^(WFServiceTableViewCell *cell, NSIndexPath *indexPath) {
        @strongify(self);
        [self onCategory];
    };

    self.phaseCell = [WFServiceTableViewCell new];
    self.phaseCell.titleLabel.text = @"发育期";
    self.phaseCell.onClick = ^(WFServiceTableViewCell *cell, NSIndexPath *indexPath) {
        @strongify(self);
        [self onPhase];
    };

    self.descSeparator = [WFSeparatorTableViewCell new];
    self.descSeparator.cellHeight = 10;
    self.descHeader = [WFServiceSectionHeaderView new];
    self.descHeader.titleLabel.text = @"详细描述";
    self.descCell = [WFWFTextViewCell new];
    self.descCell.cellHeight = 80;
    self.descCell.insets = UIEdgeInsetsMake(8, 16, 8, 16);
    
    self.imageSeparator = [WFSeparatorTableViewCell new];
    self.imageSeparator.cellHeight = 10;
    self.imageHeader = [WFServiceSectionHeaderView new];
    self.imageHeader.titleLabel.text = @"上传照片";
    self.imageCell = [WFUploadImageCell new];
    self.imageCell.cellHeight = 159;
    self.imageCell.itemSize = CGSizeMake(95, 95);
    self.footerView = [[WFButtonTableFooterView alloc] initWithFrame:CGRectMake(0, 0, 300, 50)];
    [self.footerView.saveButton addTarget:self action:@selector(onSave) forControlEvents:UIControlEventTouchUpInside];
    
    self.sections = @[
                      @[ self.cropCell, self.modeCell, self.categoryCell, self.phaseCell, self.descSeparator ],
                      @[ self.descCell, self.imageSeparator ],
                      @[ self.imageCell ],
                      ];
    
    self.tableView.tableFooterView = self.footerView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (WFPickerViewController *)pickerController {
    if (!_pickerController) {
        _pickerController = [[WFPickerViewController alloc] init];
        _pickerController.delegate = self;
    }
    return _pickerController;
}


//MARK:- table delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sections.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 40;
    }else if (section == 2) {
        return 40;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return self.descHeader;
    }else if (section == 2) {
        return self.imageHeader;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sections[section].count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = self.sections[indexPath.section][indexPath.row].cellHeight;
    if (height == 0) {
        return 50;
    }
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.sections[indexPath.section][indexPath.row];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    WFServiceTableViewCell *cell = self.sections[indexPath.section][indexPath.row];
    if ([cell isKindOfClass:[WFServiceTableViewCell class]]) {
        cell.onClick(cell, indexPath);
    }
}

//MARK:- event
- (void)onCrop {
    self.pickerController.dataSource = @[wf_cropNames];
    self.currentPickerCell = self.cropCell;
    [self presentViewController:self.pickerController
                       animated:YES
                     completion:nil];
}

- (void)onCategory {
    NSString *cropName = self.cropCell.contentLabel.text;
    if (cropName.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请选择作物"];
        return;
    }
    NSArray *categorys = wf_categoryNames[cropName];
    if (categorys.count == 0) {
        [SVProgressHUD showInfoWithStatus:@"暂无品种"];
        return;
    }
    self.currentPickerCell = self.categoryCell;
    self.pickerController.dataSource = @[categorys];
    [self presentViewController:self.pickerController
                       animated:YES
                     completion:nil];
}

- (void)onPhase {
    NSString *cropName = self.cropCell.contentLabel.text;
    if (cropName.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请选择作物"];
        return;
    }
    NSArray *phases = wf_phaseNames[cropName];
    if (phases.count == 0) {
        [SVProgressHUD showInfoWithStatus:@"暂无发育期"];
        return;
    }
    self.currentPickerCell = self.phaseCell;
    self.pickerController.dataSource = @[phases];
    [self presentViewController:self.pickerController
                       animated:YES
                     completion:nil];
}

- (void)onSave {
    if (self.imageCell.photos.count > 0) {
        NSMutableArray *images = [NSMutableArray new];
        NSMutableArray *imageNames = [NSMutableArray new];
        for (PHAsset *asset in self.imageCell.photos) {
            PHImageRequestOptions *options = [PHImageRequestOptions new];
            options.synchronous = YES;
            [[PHImageManager defaultManager] requestImageForAsset:asset
                                                       targetSize:CGSizeMake(600, 600)
                                                      contentMode:PHImageContentModeAspectFit
                                                          options:options
                                                    resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                        if (result) {
                                                            UIImage *image = [result sc_resizedImageWithWidth:600/result.scale];
                                                            [images addObject:image];
                                                            [imageNames addObject:[NSString stringFromDateWithFormat:@"yyyyMMddHHmmssSSS"]];
                                                        }
                                                    }];
        }
        [self uploadWithImages:images imageNames:imageNames];
    } else {
        [self uploadWithImages:nil imageNames:nil];
    }
}

- (void)uploadWithImages:(NSArray *)images imageNames:(NSArray *)imageNames {
    self.footerView.saveButton.enabled = NO;
    NSString *cropName = self.cropCell.contentLabel.text;
    NSString *modeName = self.modeCell.groupView.selectedIndexs.firstIndex == NSNotFound ? @"" : self.modeCell.groupView.titles[self.modeCell.groupView.selectedIndexs.firstIndex];
    NSString *categoryName = self.categoryCell.contentLabel.text;
    NSString *phaseName = self.phaseCell.contentLabel.text;

    WFServiceRequest *request = [WFServiceRequest new];
    request.desc = [NSString stringWithFormat:@"%@ %@ %@ %@ %@",
                    cropName ?: @"",
                    modeName ?: @"",
                    categoryName ?: @"",
                    phaseName ?: @"",
                    self.descCell.textView.text ?: @""
                    ];
    request.type = 1;
    request.images = images;
    request.imageNames = imageNames;
    [SVProgressHUD show];
    [request startWithBlock:^(MZBaseRequest *request, NSError *error) {
        if (error) {
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        } else {
            [SVProgressHUD showSuccessWithStatus:@"上报成功"];
        }
        self.footerView.saveButton.enabled = YES;
    }];
}

//MARK:- picker delegate
- (void)pickerViewController:(WFPickerViewController *)controller didPickAtIndexPath:(NSIndexPath *)indexPath {
    NSString *str = self.pickerController.dataSource[0][[indexPath indexAtPosition:0]];
    self.currentPickerCell.contentLabel.text = str;
}

@end
